package cn.edu.pet.servlet.admin;


import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.MultipartConfig;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.Part;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

@WebServlet("/upload")
@MultipartConfig
public class ImageUploadServlet extends HttpServlet {
    private static final String UPLOAD_DIR = "uploads";

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String uploadPath = getServletContext().getRealPath("") + File.separator + UPLOAD_DIR;
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdir();
        }
        List<String> uploadedFiles = request.getParts().stream()
                .filter(part -> "image1".equals(part.getName()) && part.getSize() > 0)
                .map(part -> {
                    try {
                        return saveFile(part, uploadPath);
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }).toList();
        String imagePath = uploadedFiles.isEmpty() ? null : uploadedFiles.get(0);
        response.setContentType("text/plain");
        response.getWriter().write("/" + UPLOAD_DIR + "/" + imagePath);
    }

    private String saveFile(Part part, String uploadPath) throws IOException {
        String fileName = UUID.randomUUID().toString().replaceAll("-", "");
        String filePath = uploadPath + File.separator + fileName;
        part.write(filePath);
        return fileName;
    }
}
